package spt.plus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spt.plus.entity.Book;
import spt.plus.mapper.BookMapper;
import spt.plus.service.IBookService;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    @Autowired
    BookMapper bookMapper;

    @Override
    public IPage getPage(Book book, Integer pageNum) {
        /*
        BaseMapper接口提供的CRUD方法中，有些方法提供了Wrapper类型的参数，用于设置查询条件，
        Wrapper类型的参数既可以使用子类QueryWrapper对象，也可以使用子类LambdaQueryWrapper对象。
        上面使用QueryWrapper封装查询条件时各个属性是手打的字符串，容易出错，
        而使用LambdaQueryWrapper封装查询条件时可以使用Lambda表达式，可以调用各个属性，从而避免这个错误。
         */

//        QueryWrapper queryWrapper=new QueryWrapper();
//        if (book.getName() != null && book.getName() != "") {
//            queryWrapper.like("name",book.getName());
//        }
//        if (book.getAuthor() != null && book.getAuthor() != "") {
//            queryWrapper.eq("author",book.getAuthor());
//        }
//        return bookMapper.selectList(queryWrapper);

        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        if (book.getName() != null && book.getName() != "") {
            queryWrapper.like(Book::getName, book.getName());
        }
        if (book.getAuthor() != null && book.getAuthor() != "") {
            queryWrapper.eq(Book::getAuthor, book.getAuthor());
        }

        IPage page=new Page(pageNum,3);
        return bookMapper.selectPage(page,queryWrapper);
    }

    @Override
    public Book getInfo(Integer id) {
        return bookMapper.selectById(id);
    }

    @Override
    public void addOrUpdate(Book book) {
        if (book.getId()==null) {
            bookMapper.insert(book);
        }else {
            bookMapper.updateById(book);
        }
    }

    @Override
    public void delBook(String[] id) {
        for (String s : id) {
            LambdaQueryWrapper<Book> warpper =new LambdaQueryWrapper<Book>().eq(Book::getId,s);
            bookMapper.delete(warpper);
        }
    }
}
